package com.siboxuetang.need.web.interceptor;

import com.siboxuetang.need.util.ResultCode;
import com.siboxuetang.need.util.SessionUtils;
import com.siboxuetang.need.util.WebUtils;
import com.siboxuetang.need.vo.NeedException;
import com.siboxuetang.need.vo.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StreamUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create Time: 2018年03月07日 14:04
 *
 * @author fin
 */
public class AuthInterceptor extends AbstractInterceptor{

    private Logger logger = LogManager.getLogger(AuthInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("request from {}, location: {}, method: {}, data: {}", WebUtils.getRemoteClientIp(httpServletRequest),httpServletRequest.getRequestURL().toString(),httpServletRequest.getMethod(), StreamUtils.copyToByteArray(httpServletRequest.getInputStream()));
        User user = SessionUtils.getSession(httpServletRequest, "_user", User.class);
        if(!isPublic((HandlerMethod) o)){
            if(user == null) {
                throw new NeedException(ResultCode.NO_USER_AUTH, "不明用户试图访问非公开api : " + httpServletRequest.getRequestURI());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
